<template>
  <div class="user-profile">
    <!-- 头像缓存状态组件 (仅在开发环境显示) -->
    <AvatarCacheStats v-if="process.env.NODE_ENV === 'development'" />
    
    <!-- 个人信息卡片 -->
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
        </div>
      </template>
      
      <div class="profile-content">
        <!-- 头像上传区域 -->
        <div class="avatar-section">
          <div class="avatar-container">
            <el-upload
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadAvatar"
              accept="image/*"
              class="avatar-uploader"
            >
              <el-avatar 
                :size="120" 
                :src="cachedAvatarUrl" 
                class="avatar-display"
              />
              <div class="avatar-overlay">
                <el-icon class="avatar-icon"><Camera /></el-icon>
                <span>点击更换头像</span>
              </div>
            </el-upload>
          </div>
        </div>

        <!-- 个人信息表单 -->
        <el-form
          ref="profileFormRef"
          :model="userForm"
          :rules="profileRules"
          label-width="100px"
          class="profile-form"
        >
          <el-form-item label="姓名" prop="username">
            <el-input v-model="userForm.username" />
          </el-form-item>
          
          <el-form-item label="性别" prop="gender">
            <el-select v-model="userForm.gender" placeholder="请选择性别">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="联系电话" prop="telephone">
            <el-input v-model="userForm.telephone" />
          </el-form-item>
          
          <el-form-item label="联系地址" prop="address">
            <el-input v-model="userForm.address" type="textarea" :rows="3" />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="updateProfile" :loading="profileLoading">
              更新资料
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 用户密码修改卡片 -->
    <el-card class="user-password-card">
      <template #header>
        <div class="card-header">
          <span>修改登录密码</span>
          <el-tag type="info" size="small">账户安全</el-tag>
        </div>
      </template>
      
      <div class="password-content">
        <div class="password-tips">
          <el-alert
            title="安全提示"
            description="为了您的账户安全，建议定期更改密码。密码应包含字母和数字，长度不少于6位。"
            type="info"
            show-icon
            :closable="false"
          />
        </div>
        
        <el-form
          ref="userPasswordFormRef"
          :model="userPasswordForm"
          :rules="userPasswordRules"
          label-width="120px"
          class="password-form"
        >
          <el-form-item label="当前密码" prop="oldPassword">
            <el-input 
              v-model="userPasswordForm.oldPassword" 
              type="password" 
              show-password
              placeholder="请输入当前登录密码"
            />
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input 
              v-model="userPasswordForm.newPassword" 
              type="password" 
              show-password
              placeholder="请输入新密码（至少6位）"
            />
          </el-form-item>
          
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input 
              v-model="userPasswordForm.confirmPassword" 
              type="password" 
              show-password
              placeholder="请再次输入新密码"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="changeUserPassword" :loading="userPasswordLoading">
              修改密码
            </el-button>
            <el-button @click="resetUserPasswordForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 银行卡密码修改卡片 -->
    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <span>银行卡密码管理</span>
          <el-tag type="warning" size="small">银行卡安全</el-tag>
        </div>
      </template>
      
      <div class="password-content">
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="120px"
          class="password-form"
        >
          <el-form-item label="选择银行卡" prop="cardid">
            <el-select v-model="passwordForm.cardid" placeholder="请选择要修改密码的银行卡">
              <el-option
                v-for="card in userCards"
                :key="card.cardid"
                :label="`${card.cardid} (余额: ¥${card.balance})`"
                :value="card.cardid"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="当前密码" prop="oldPassword">
            <el-input 
              v-model="passwordForm.oldPassword" 
              type="password" 
              show-password
              placeholder="请输入当前银行卡密码"
            />
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input 
              v-model="passwordForm.newPassword" 
              type="password" 
              show-password
              placeholder="请输入新密码"
            />
          </el-form-item>
          
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input 
              v-model="passwordForm.confirmPassword" 
              type="password" 
              show-password
              placeholder="请再次输入新密码"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="changePassword" :loading="passwordLoading">
              修改银行卡密码
            </el-button>
            <el-button @click="resetPasswordForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Camera } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import { cardApi } from '@/api/card'
import avatarCache from '@/utils/avatarCache'
import AvatarCacheStats from '@/components/AvatarCacheStats.vue'

// 表单引用
const profileFormRef = ref()
const passwordFormRef = ref()
const userPasswordFormRef = ref()

// 加载状态
const profileLoading = ref(false)
const passwordLoading = ref(false)
const userPasswordLoading = ref(false)

// 用户卡片数据
const userCards = ref([])

// 个人信息表单
const userForm = reactive({
  username: '',
  gender: '',
  telephone: '',
  address: '',
  imageurl: ''
})

// 头像缓存处理
const cachedAvatarUrl = computed(() => {
  return avatarCache.getCachedAvatar(userForm.imageurl)
})

// 监听头像URL变化，预加载新头像
watch(() => userForm.imageurl, (newUrl, oldUrl) => {
  if (newUrl && newUrl !== oldUrl) {
    avatarCache.preloadImage(newUrl).then(() => {
      // 预加载完成后可以做一些处理，比如刷新显示
      console.log('头像预加载完成:', newUrl)
    })
  }
})

// 用户密码修改表单
const userPasswordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 银行卡密码修改表单
const passwordForm = reactive({
  cardid: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const profileRules = {
  username: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  telephone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 用户密码验证规则
const userPasswordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== userPasswordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 银行卡密码验证规则
const passwordRules = {
  cardid: [
    { required: true, message: '请选择银行卡', trigger: 'change' }
  ],
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const loadUserInfo = async () => {
  try {
    const response = await userApi.getUserInfo()
    if (response && response.data) {
      Object.assign(userForm, response.data)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 获取用户银行卡列表
const loadUserCards = async () => {
  try {
    const response = await userApi.getUserCards()
    if (response && response.data) {
      userCards.value = response.data
    }
  } catch (error) {
    console.error('获取银行卡列表失败:', error)
  }
}

// 头像上传前检查
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义头像上传
const uploadAvatar = async (options) => {
  try {
    console.log('🚀 开始头像上传流程:', {
      fileName: options.file.name,
      fileSize: options.file.size,
      fileType: options.file.type,
      fileObject: options.file
    })
    
    // 检查是否有token
    const token = document.cookie.split(';').find(row => row.trim().startsWith('token='))
    if (!token) {
      ElMessage.error('未登录，请先登录')
      return
    }
    
    console.log('✅ Token检查通过:', {
      hasToken: !!token,
      tokenLength: token ? token.length : 0
    })
    
    // 调用API上传头像 - 这里会进入我们的axios配置流程
    console.log('📡 调用userApi.uploadImage...')
    const response = await userApi.uploadImage(options.file)
    
    console.log('📥 头像上传API响应:', {
      response,
      hasData: !!response?.data,
      dataValue: response?.data
    })
    
    if (response && response.data) {
      // 清除旧头像缓存（如果有的话）
      if (userForm.imageurl) {
        avatarCache.updateAvatar(userForm.imageurl)
      }
      
      // 更新头像URL
      userForm.imageurl = response.data
      
      // 立即预加载新头像到缓存
      avatarCache.preloadImage(response.data)
      
      ElMessage.success('头像上传成功！')
      console.log('✅ 头像URL已更新:', response.data)
    } else {
      console.error('❌ 头像上传失败: 响应格式不正确', response)
      ElMessage.error('头像上传失败，响应格式错误')
    }
  } catch (error) {
    console.error('❌ 头像上传异常:', {
      message: error.message,
      response: error.response,
      responseData: error.response?.data,
      status: error.response?.status,
      config: error.config,
      stack: error.stack
    })
    
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
    } else {
      const errorMsg = error.response?.data?.message || error.message || '未知错误'
      ElMessage.error(`头像上传失败: ${errorMsg}`)
    }
  }
}

// 更新个人资料
const updateProfile = async () => {
  if (!profileFormRef.value) return

  try {
    await profileFormRef.value.validate()
    profileLoading.value = true

    const updateData = {
      username: userForm.username,
      gender: userForm.gender,
      telephone: userForm.telephone,
      address: userForm.address,
      imageurl: userForm.imageurl
    }

    const response = await userApi.updateProfile(updateData)
    if (response && (response.code === 0 || response.data === true)) {
      ElMessage.success('个人资料更新成功')
    } else {
      ElMessage.error('个人资料更新失败')
    }
  } catch (error) {
    console.error('更新个人资料失败:', error)
    ElMessage.error('更新个人资料失败')
  } finally {
    profileLoading.value = false
  }
}

// 修改用户登录密码
const changeUserPassword = async () => {
  if (!userPasswordFormRef.value) return

  try {
    await userPasswordFormRef.value.validate()
    
    await ElMessageBox.confirm(
      '确认要修改登录密码吗？修改后需要重新登录。',
      '确认修改',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    userPasswordLoading.value = true

    const changeData = {
      oldPassword: userPasswordForm.oldPassword,
      newPassword: userPasswordForm.newPassword
    }

    const response = await userApi.changeUserPassword(changeData)
    if (response && (response.code === 0 || response.data === true)) {
      ElMessage.success('用户密码修改成功，请重新登录')
      resetUserPasswordForm()
      
      // 延迟1秒后跳转到登录页面
      setTimeout(() => {
        // 清除token和用户信息
        document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/;'
        localStorage.removeItem('userInfo')
        localStorage.removeItem('token')
        
        // 跳转到登录页面
        window.location.href = '/login'
      }, 1000)
    } else {
      ElMessage.error('用户密码修改失败，请检查当前密码是否正确')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改用户密码失败:', error)
      ElMessage.error('修改用户密码失败')
    }
  } finally {
    userPasswordLoading.value = false
  }
}

// 修改银行卡密码
const changePassword = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    
    await ElMessageBox.confirm(
      '确认要修改选中银行卡的密码吗？',
      '确认修改',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    passwordLoading.value = true

    const changeData = {
      cardid: passwordForm.cardid,
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    }

    const response = await cardApi.changePassword(changeData)
    if (response && (response.code === 0 || response.data === true)) {
      ElMessage.success('银行卡密码修改成功')
      resetPasswordForm()
    } else {
      ElMessage.error('银行卡密码修改失败，请检查当前密码是否正确')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改银行卡密码失败:', error)
      ElMessage.error('修改银行卡密码失败')
    }
  } finally {
    passwordLoading.value = false
  }
}

// 重置用户密码表单
const resetUserPasswordForm = () => {
  userPasswordFormRef.value?.resetFields()
  Object.assign(userPasswordForm, {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
}

// 重置银行卡密码表单
const resetPasswordForm = () => {
  passwordFormRef.value?.resetFields()
  Object.assign(passwordForm, {
    cardid: '',
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadUserInfo()
  loadUserCards()
})
</script>

<style scoped>
.user-profile {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.profile-card,
.user-password-card,
.password-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
}

.profile-content,
.password-content {
  padding: 20px 0;
}

.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.avatar-container {
  position: relative;
  cursor: pointer;
}

.avatar-uploader {
  position: relative;
  border-radius: 50%;
  overflow: hidden;
}

.avatar-display {
  transition: all 0.3s ease;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  border-radius: 50%;
  font-size: 14px;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.profile-form,
.password-form {
  max-width: 500px;
}

.password-tips {
  margin-bottom: 20px;
}

.user-password-card {
  border-left: 4px solid #409eff;
}

.password-card {
  border-left: 4px solid #e6a23c;
}

.user-password-card .card-header {
  color: #409eff;
}

.password-card .card-header {
  color: #e6a23c;
}

@media (max-width: 768px) {
  .user-profile {
    padding: 10px;
  }
  
  .profile-form,
  .password-form {
    max-width: 100%;
  }
}
</style> 